package com.ccit.course.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ccit.common.client.IntegralClient;
import com.ccit.common.client.MoneyClient;
import com.ccit.common.client.UserClient;
import com.ccit.common.exception.GymException;
import com.ccit.common.result.Result;
import com.ccit.common.utils.PageUtil;
import com.ccit.common.utils.RedisUtils;
import com.ccit.course.service.CourseOrderService;
import com.ccit.model.CourseOrder;
import com.ccit.model.Integral;
import com.ccit.model.User;
import com.ccit.model.vo.money.MoneyVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;

@RestController
@Api(tags = "课程订单")
@RequestMapping("/courseOrder")
public class CourseOrderController {

    @Autowired
    private CourseOrderService courseOrderService;

    @Autowired
    private UserClient userClient;

    @Autowired
    private MoneyClient moneyClient;

    @Autowired
    private IntegralClient integralClient;

    @Autowired
    private RedisUtils redisUtils;


    @ApiOperation(value = "分页查询课程订单")
    @GetMapping("/listByPage/{current}/{size}")
    public Result listByPage(@PathVariable Integer current,
                             @PathVariable Integer size) {
        List<CourseOrder> allOrder;
        String key = "courseAllOrder";
        boolean has = redisUtils.hasKey(key);
        if (has) {
            allOrder = (List<CourseOrder>) redisUtils.get(key);
        } else {
            allOrder = courseOrderService.findAllOrder();
            redisUtils.set(key, allOrder, 60 * 120 * 24 * 7);
        }
        Page pages = PageUtil.getPages(current, size, allOrder);
        return Result.ok(pages);
    }


    @ApiOperation(value = "查询所有课程订单")
    @GetMapping("/listAll")
    public Result listAll() {
        List<CourseOrder> allOrder;
        String key = "courseAllOrder";
        boolean has = redisUtils.hasKey(key);
        if (has) {
            allOrder = (List<CourseOrder>) redisUtils.get(key);
        } else {
            allOrder = courseOrderService.findAllOrder();
            redisUtils.set(key, allOrder, 60 * 120 * 24 * 7);
        }
        return Result.ok(allOrder);
    }

    @ApiOperation(value = "分页查询指定手机号课程订单")
    @GetMapping("/getByPhone/{phone}/{current}/{size}")
    public Result getByPhone(@PathVariable String phone,
                             @PathVariable Integer current,
                             @PathVariable Integer size) {
        List<CourseOrder> list;
        String key = "courseOrderPhone:" + phone;
        boolean has = redisUtils.hasKey(key);
        if (has) {
            list = (List<CourseOrder>) redisUtils.get(key);
        } else {
            list = courseOrderService.findOrderByPhone(phone);
            redisUtils.set(key, list, 60 * 120 * 24 * 7);
        }

        if (list == null) {
            throw new GymException(202, "没有此手机号");
        } else {
            Page page = PageUtil.getPages(current, size, list);
            return Result.ok(page);
        }

    }

    @ApiOperation(value = "添加新课程订单")
    @PostMapping("/saveOrder")
    public Result saveOrder(@RequestBody CourseOrder courseOrderVo) {

        CourseOrder order = new CourseOrder();
        order.setCourseId(courseOrderVo.getCourseId());
        order.setMemberPhone(courseOrderVo.getMemberPhone());
        List<CourseOrder> list = courseOrderService.findOrderList(order);
        if (list.size() > 0) {
            return Result.fail("该课程已被您购买");
        }

        /*User user = userClient.getByPhone(courseOrderVo.getMemberPhone());
        if (user ==null){
            throw new GymException(202,"不是会员");
        }*/

        CourseOrder courseOrder = new CourseOrder();
        courseOrder.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        courseOrder.setCourseId(courseOrderVo.getCourseId());
        courseOrder.setCourse(courseOrderVo.getCourse());
        courseOrder.setMemberPhone(courseOrderVo.getMemberPhone());
        courseOrder.setCoach(courseOrderVo.getCoach());
        courseOrder.setPrice(courseOrderVo.getPrice());
        courseOrder.setTime(new Date());

        Boolean result = courseOrderService.saveOrder(courseOrder);
        if (result) {
            Integral integral = new Integral();
            integral.setIntegral((int) (Math.round(order.getPrice() / 100)));
            integral.setPhone(order.getMemberPhone());
            Boolean b = integralClient.updateIntegral(integral);

            MoneyVo moneyVo = new MoneyVo();
            moneyVo.setMoneyType("收入");
            moneyVo.setTypeName("课程订单");
            moneyVo.setAmout(courseOrder.getPrice());
            boolean b1 = moneyClient.apiSaveMoney(moneyVo);
            if (!b1) {
                throw new GymException(301, "添加课程订单资金记录失败");
            }
            if (!b) {
                throw new GymException(301, "更新积分出错");
            }
            redisUtils.deleteRedisKeys("courseAllOrder");
            redisUtils.deleteRedisKeys("courseOrderPhone");
            return Result.ok("购买成功");
        } else {
            return Result.fail().message("添加失败");
        }
    }

    //mysql转mongodb
    @GetMapping("/get")
    public Result selectOrderMysql() {
        List<CourseOrder> list = courseOrderService.list();
        list.forEach(order -> {
            courseOrderService.saveOrder(order);
        });
        List<CourseOrder> allOrder = courseOrderService.findAllOrder();
        return Result.ok(allOrder);
    }
}
